<template>
  <div class="content-wrapper">
    <el-row type="flex" :gutter="20" style="padding-left: 1vw">
      <el-col :span="4">
        <h2 class="subtitle" style="margin-top: 3vh; margin-left: 1vw">用户管理</h2>
      </el-col>
      <el-col :span="19">
        <el-form :inline="true" class="demo-form-inline" style="margin: 2vh 0 0 2vw;">
          <el-form-item>
            <div slot="label" style="color:white; font-size: 20px;">
              用户名：
            </div>
            <el-input v-model="username"></el-input>
          </el-form-item>
          <el-button class="el-blue-button" @click="getUsers"><i class="el-icon-search"></i> &nbsp;查询</el-button>
          <el-button class="el-blue-button" @click="reset"><i class="el-icon-refresh-right"></i>&nbsp;重置</el-button>
          <el-button class="el-blue-button" style="float: right;margin-right: 20px" @click="recover">还原默认配置</el-button>
          <el-button class="el-blue-button" style="float: right;margin-right: 20px" @click="addUsers('新增通知')"><i class="el-icon-plus"></i>&nbsp;新增</el-button>
        </el-form>
      </el-col>
    </el-row>
    <el-row style="margin: 0 5vw">
      <el-table
        :data="users"
        style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
        <el-table-column prop="name" label="用户名" align="center"></el-table-column>
        <el-table-column prop="typename" label="职位" align="center" width="400"></el-table-column>
        <el-table-column label="操作" width="230" align="center">
          <template slot-scope="scope">
            <el-button class="el-green-button" size="mini" @click="goViewWithQuery('查看', scope.row)">查看</el-button>
            <el-button class="el-blue-button" size="mini" @click="goViewWithQuery('编辑', scope.row)">修改</el-button>
            <el-button class="el-red-button" size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px;float: right"
        :page-size="8"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next, jumper"
        :current-page.sync="currentPage"
        :total=total />
    </el-row>
    <user-dialog :visible-flag='userDialogForm' :userform="userform" @close-dialog="closeUserDialog"></user-dialog>
    <currency-dialog :visible-flag='addDialogForm' :userform="addform" :rules="currencyRules"
                     @close-dialog="closeCurrencyDialog" :dialogKind="dialogKind" :userId="userId"></currency-dialog>
  </div>
</template>

<script>
import request from '@/network/request'
import userDialog from './userDialog'
import currencyDialog from './currencyDialog'
export default {
  name: 'index',
  components: {
    userDialog,
    currencyDialog
  },
  data () {
    const userForm = {
      type: '',
      typename: '',
      name: '',
      password: '',
      pw_repeat: ''
    }
    // 校验职级输入为0~1之间
    // var checkPermissionlv = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('职级不能为空'))
    //   }
    //   setTimeout(() => {
    //     var numReg = /^[0-9]*$/
    //     var numRe = new RegExp(numReg)
    //     if (!numRe.test(value)) {
    //       callback(new Error('请输入数字值'))
    //     } else {
    //       if (value < 0 || value > 1) {
    //         callback(new Error('职级为0~1之间，0为管理员，1为普通用户'))
    //       }
    //     }
    //   }, 10)
    // }
    return {
      userForm,
      dialogKind: 0, // 0:修改信息dialog；1：增加信息dialog
      username: '',
      userDialogForm: false,
      addDialogForm: false,
      users: [],
      userform: this.easyClone(userForm),
      addform: this.easyClone(userForm),
      currencyRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '长度不少于6个字符', trigger: 'blur' }
        ],
        pw_repeat: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 6, message: '长度不少于6个字符', trigger: 'blur' }
        ],
        typename: [
          { required: true, message: '请输入职位', trigger: 'blur' }
        ]
        // type: [
        //   { validator: checkPermissionlv, trigger: 'blur' }
        // ]
      },
      loading: true,
      total: 0,
      currentPage: 1,
      pageSize: 8,
      userId: ''
    }
  },
  beforeMount () {
    this.reset()
  },
  methods: {
    goViewWithQuery (name, data) {
      switch (name) {
        case '查看': {
          this.userDialogForm = true
          this.userform = data
          break
        }
        case '编辑': {
          this.dialogKind = 0
          this.addDialogForm = true
          this.addform = data
          this.userId = data.id.toString()
          break
        }
      }
    },
    handleDelete (index, row) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          method: 'post',
          url: '/userOp/delete',
          params: {
            id: row.id
          }
        }).then((res) => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.requestUserList()
          } else {
            this.$message.error('删除失败!')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getUsers () {
      this.requestUserList()
    },
    addUsers () {
      this.dialogKind = 1
      this.addform = this.easyClone(this.userForm)
      this.addDialogForm = true
    },
    reset () {
      this.username = ''
      this.currentPage = 1
      this.requestUserList()
    },
    requestUserList () {
      this.loading = true
      request({
        method: 'post',
        url: '/userOp/select',
        params: {
          name: this.username,
          pageSize: this.pageSize,
          page: this.currentPage
        }
      }).then((res) => {
        this.users = res.data.data.user
        this.total = res.data.data.sum
        this.loading = false
      })
    },
    /**
     * 通过JSON转换的方式进行简单的深克隆
     * 不支持属性中含有函数、正则，只支持标准JSON格式的对象
     * @param obj Object
     * @return Object
     */
    easyClone (obj) {
      return JSON.parse(JSON.stringify(obj))
    },
    closeUserDialog () {
      this.userDialogForm = false
    },
    closeCurrencyDialog () {
      this.addDialogForm = false
      this.requestUserList()
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.requestUserList()
    },
    recover () {
      this.$confirm('确定恢复到默认配置吗（其中包含：规则、点位、用户的数据）').then(() => {
        request({
          method: 'get',
          url: '/DBOp/backupDB'
        }).then((res) => {
          this.$alert(res.data.message)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .demo-form-inline {
    padding-top: 0.8vh;
  }
  .el-table{
    font-size: 20px;
  }
  >>>td .cell {
    /*margin-top: 3vh;*/
    margin: 1% 0;
  }
  .pagination {
    padding-top: 2vh;
    text-align: center;
  }
  >>>.el-pagination__total, >>>.el-pagination__jump{
    color: white;
  }
  >>> .el-pagination span {
    font-size: 18px;
  }
  >>>.number{
    color: #dddddd;
  }
</style>
